from py2neo import Graph, Node, NodeMatcher, RelationshipMatcher, Relationship
import re
import jieba
import jieba.posseg as preg


graph = Graph("bolt://localhost:7687", username="neo4j", password='1998')
matcher = NodeMatcher(graph)
rmatcher = RelationshipMatcher(graph)


def drug():
    print('去药物名中的空格和制药公司')
    # 去药物中的空格
    drugs = matcher.match('drug')
    for drug in drugs:
        name = drug['name'].split(' ')
        print(name)
        if len(name) == 2:
            print(name)
            drug['name'] = name[1]
            drug.update({'name': name[1]})
            graph.push(drug)


def infect():
    disease = matcher.match('disease')
    infect_set = set()
    for disease in disease:
        if disease.get('infect') is not None:
            infect = ' '.join(disease['infect'])
            if "无传染性" == infect:
                disease['infect'] = ""
                graph.push(disease)
                print(infect)
            elif "无传染性" in infect or "不传染" in infect:
                disease['infect'] = ""
                graph.push(disease)
                print(infect)
            elif "无" in infect or "非" in infect or "没有" in infect:
                disease['infect'] = ""
                graph.push(disease)
                print(infect)
            elif "通过" in infect:
                infect = re.sub(r"部分.*通过|通过.*等|有些通过|通过", '', infect)
                infect = re.sub(r"，亦可粘膜或皮肤破损处而进入人体。|病毒经唾液，气管分泌物及尿液排出，幼儿与父母|而感染|都有传染的可能|先天性由|后天性主要|有些病原体性|分为内源性和外源性两方面。内源性自身的|外源性主要是|可以传播，也可|衣物用具而|人与人之间|。", '', infect)
                infect = re.sub(r"性生活|性接触", '性', infect)
                infect = re.sub(r"呼吸道分泌物", '呼吸道', infect)
                infect = re.sub(r"亲密|密切", '直接', infect)
                infect = re.sub(r"传播|传染|传染性|感染|感染性", '', infect)
                infect = re.sub(r"[,，、.]|和|或", ' ', infect)
                # print(infect.split(' '))
                for infect in infect.split(' '):
                    if infect != "":
                        print(infect)
                        node_infect = matcher.match('infect').where(f"_.name='{infect}'").first()
                        if node_infect is None:
                            print('none')
                            node_infect = Node('infect', name=infect)
                    disease_infect = Relationship(disease, 'disease_infect', node_infect)
                    graph.create(disease_infect)
                disease['infect'] = ""
                graph.push(disease)
            elif "有传染" in infect or "会传染" in infect or "有一定传染性" in infect or "传染性较低" in infect:
                infect = re.sub(r"传染方式主要是|上呼吸道感染为最常见原因，|感染性腹泻|多继发于急性鼻炎，发病初期|部分|属于结核，|根据被复苏对象是否患有传染性疾病及患有何种传染性疾病而定|个别眼病|不确定，如是病毒性肝炎后肝硬化则", '', infect)
                infect = re.sub(r"接触有传染性", '接触 有传染性', infect)
                infect = re.sub(r"有些会传染|有一定传染性|传染性较低", '有传染性', infect)
                infect = re.sub(r"密切", '直接', infect)
                infect = re.sub(r"传播", '', infect)
                infect = re.sub(r"[,，、.]|和|或", ' ', infect)
                print(infect.split(' '))
                for infect in infect.split(' '):
                    if infect != "":
                        print(infect)
                        node_infect = matcher.match('infect').where(f"_.name='{infect}'").first()
                        if node_infect is None:
                            print('none')
                            node_infect = Node('infect', name=infect)
                        disease_infect = Relationship(disease, 'disease_infect', node_infect)
                        graph.create(disease_infect)
                disease['infect'] = ""
                graph.push(disease)
            elif "经" in infect or "大多" in infect or "部分" in infect or "通常" in infect or "由" in infect or "的" in infect or "依" in infect or "为" in infect:
                # infect = re.sub(r"部分|经|由|的", '', infect)
                infect = re.sub(r"肺病可|侵入|而传染|也可以经过|还可以经过|另外苍蝇携带|，可由污染的牛奶和食物传染|也可以传播本病|未消毒的|患者或带菌者的|皮肤及粘膜|依据病原体，区别对待|大多由皮肤或(与)黏膜侵入|密切接触为主要传播途径，飞沫传播虽有可能，但并不重要|病因为病毒感染或者细菌感染，多由", '', infect)
                infect = re.sub(r"部分|经|由|的|主要|大多", '', infect)
                infect = re.sub(r"性生活|性接触|性交", '性', infect)
                infect = re.sub(r"亲密|密切", '直接', infect)
                infect = re.sub(r"[,，、.。]|和|或|\(与\)", ' ', infect)
                infect = re.sub(r"\d", '', infect)
                infect = re.sub(r"传播|传染|传染性|感染|感染性", '', infect)
                a = 1
                # print(infect.split(' '))
                for infect in infect.split(' '):
                    if infect != "":
                        print(infect)
                        node_infect = matcher.match('infect').where(f"_.name='{infect}'").first()
                        if node_infect is None:
                            print('none')
                            node_infect = Node('infect', name=infect)
                        disease_infect = Relationship(disease, 'disease_infect', node_infect)
                        graph.create(disease_infect)
                disease['infect'] = ""
                graph.push(disease)
            elif infect != "":
                infect = re.sub(r"人与人|生活|以|等|有", '', infect)
                infect = re.sub(r"呼吸道分泌物", '呼吸道 ', infect)
                infect = re.sub(r"性生活|性接触|性交", '性', infect)
                infect = re.sub(r"粪-口途径|粪口途径|粪-口|粪口", '粪-口途径', infect)
                infect = re.sub(r"母婴垂直|母-婴", '母婴', infect)
                infect = re.sub(r"蚊虫媒介|蚊虫叮咬|蚊虫", '蚊虫叮咬', infect)
                infect = re.sub(r"血源性|血液播散", '血液', infect)
                infect = re.sub(r"接触性", '接触', infect)
                infect = re.sub(r"肠道阿米巴", '肠道菌', infect)
                infect = re.sub(r"媒介动物", '动物', infect)
                infect = re.sub(r"自身接种|自体接种", '自体接种', infect)
                infect = re.sub(r"亲密|密切", '直接', infect)
                infect = re.sub(r"[,，、.。]|和|或|\(与\)|及", ' ', infect)
                infect = re.sub(r"\d", '', infect)
                infect = re.sub(r"传播|传染性|传染|感染性|感染", '', infect)
                # print(infect)
                for infect in infect.split(' '):
                    if infect != "":
                        print(infect)
                        node_infect = matcher.match('infect').where(f"_.name='{infect}'").first()
                        if node_infect is None:
                            print('none')
                            node_infect = Node('infect', name=infect)
                        disease_infect = Relationship(disease, 'disease_infect', node_infect)
                        graph.create(disease_infect)
                disease['infect'] = ""
                graph.push(disease)

    # infect_set.add(infect.strip())
    # #
    # for infect in infect_set:
    #     print(infect)
    # print(len(infect_set))


def form():
    form = matcher.match('form')
    for form in form:
        # name = form['name']
        name = re.sub(r"⑴", '', form['name'])
        name = re.sub(r"\)⑵丸剂\(", ' ', name)
        name = re.sub(r"（", '(', name)
        name = re.sub(r"）", ')', name)
        name = re.sub(r"[ 、，,或/;]", ' ', name)
        # print(name)
        if name.find('(') != -1:

            form = name[:name.find('(')]
            print(form)
            form_ex = name[name.find('(')+1:name.find(')')]
            print(','.join(form_ex.split(' ')))


def alias():
    disease = matcher.match('disease')
    for disease in disease:
        # print(disease.get('alias'))
        if disease.get('alias') is not None:
            alias = disease['alias']
            print(alias)


def avoid():
    drug = matcher.match('drug')
    word_dict = {}
    for drug in drug:
        # print(disease.get('alias'))
        if drug.get('avoid') is not None:
            avoid = drug['avoid']
            print(avoid, end="\n\n")
            words = jieba.cut(avoid)
            # print('/'.join(words))
            for word in words:
                if word_dict.get(word) is not None:
                   word_dict[word] += 1
                else:
                    word_dict[word] = 1
                    # print(word)
    avoid_dict = dict(sorted(word_dict.items(), key= lambda kv:(kv[1], kv[0]), reverse=True))
    print(avoid_dict)
    for key, value in avoid_dict.items():
        print(f"{key},{value}")


def population():
    disease = matcher.match('disease')
    population_set = set()
    for disease in disease:
        if disease.get('population') is not None:
            population = ' '.join(disease['population'])
            if '无' in population and len(population) < 10:
                disease['population'] = ""
                graph.push(disease)
                print(population)
            # elif '无' in population and len(population) > 10:
            #     a = 2
            #     print(population)
            #  and '者最' in population and '多' in population
            elif '男' in population:
                # print(population)
                # 7
                population = re.sub(r"心脏病或周围血管病的病史的|外阴黏膜白斑病|口腔黏膜白斑病|，高血脂，高血压，糖尿病，腹型肥胖及早发心血管病|慢性结肠炎患者、结肠息肉患者、", ' ',
                                    population)
                # 6
                population = re.sub(r"各类型人群都是可|患病年龄超过|发病者最多见|本病多起病于|大多数病例发生于|发病自幼年开始|但2/3病例发生在", ' ', population)
                # 5
                population = re.sub(
                    r"无特定人群|多数患者为|多3～13倍|以上最多见|发生率高于|也可发生在|主要发生在|该病好发于|好发年龄为|年岁分布于|无特殊人群|HIV感染者|经常日晒的|发病只占15%|IPH通常在|皮肤血管瘤|患者年龄在",
                    ' ', population)
                # 4
                population = re.sub(
                    r"往往不顾|可发生于|主要见于|发病率高|多发生在|大多见于|之比率为|患儿居多|较肥胖的|患者略多|本病罕见|多发生于|发病年龄|更易感染|尤其是在|发病最多|较多发于|之前发病|均可发病|以前发病|都有可能",
                    ' ', population)
                # 3
                population = re.sub(
                    r"聚集性|易感性|四十岁|者居多|闭经后|常见于|的3倍|对见于|大多为|为最多|为多见|略多于|无明显|主要以|仅见于|多数为|大多在|中发病|无差异|但多在|既往有|稍多于|常发于|多见于|发生于|多发于|年龄为|主要是|之比为|发病率|患病率|比例为|尤其是|多数是",
                    ' ', population)
                # 2
                population = re.sub(
                    r"跳水|仅限|特点|冲动|传播|气体|几乎|任何|阶段|两个|高峰|常起|最多|起病|不同|本病|该病|年龄|为多|绝经|少于|较多|左右|约占|少见|病人|肾癌|发病|多与|之间|以后|约为|平均|居多|发生|多见|多于|见于|好发|常在|发于|多发|多在|可在|以上|以下|尤其|一般|多为|比例|略多|患者",
                    ' ', population)
                # 1
                population = re.sub(r"如|易|曾|且|常|现|史|者|均|在|高|有|岁|但|比|于|的|以|较|等|为|在|略|见|占|期|段", ' ', population)
                population = re.sub(r"或|和|及|[,，、。]", ' ', population)
                #
                population = re.sub(r"男性|男", ' 男 ', population)
                population = re.sub(r"女性|女", ' 女 ', population)
                population = re.sub(r"孩子|孩", ' 孩子 ', population)
                population = re.sub(r"发育", ' 发育 ', population)
                population = re.sub(r"新生儿", ' 新生儿 ', population)
                population = re.sub(r"婴儿|婴", ' 婴儿 ', population)
                population = re.sub(r"幼儿", ' 幼儿 ', population)
                population = re.sub(r"学龄前", ' 学龄前 ', population)
                population = re.sub(r"儿童|童", ' 儿童 ', population)
                population = re.sub(r"青春", ' 青春 ', population)
                population = re.sub(r"青年人|青年", '青年 ', population)
                population = re.sub(r"青少年人|青少年", ' 青少年 ', population)
                population = re.sub(r"中青年人|中青年", ' 中青年 ', population)
                population = re.sub(r"青壮年人|青壮年", ' 青壮年 ', population)
                population = re.sub(r"年轻人|年轻", ' 年轻 ', population)
                population = re.sub(r"青中年人|青中年", '青中年 ', population)
                population = re.sub(r"中年人|中年", '中年 ', population)
                population = re.sub(r"成年人|成年|成人", ' 成年 ', population)
                population = re.sub(r"中老年人|中老年", ' 中老年 ', population)
                population = re.sub(r"老年人|老年", '老年 ', population)
                population = re.sub(r"", '-', population)

                population = re.sub(r"\d|-|—|－|～|~|\.|:|∶|%|/", '', population)
                # print(population.split(' '))
                for population in population.split(' '):
                    # print(population)
                    population_set.add(population)
                # print(population)
            elif "女" in population and '多' in population:
                print(population)
                # 7
                population = re.sub(
                    r"分娩过程中多次插导尿管|心脏病或周围血管病的病史的|外阴黏膜白斑病|口腔黏膜白斑病|，高血脂，高血压，糖尿病，腹型肥胖及早发心血管病|慢性结肠炎患者、结肠息肉患者、", ' ',
                    population)
                # 6
                population = re.sub(r"各类型人群都是可|患病年龄超过|发病者最多见|本病多起病于|大多数病例发生于|发病自幼年开始|但2/3病例发生在", ' ', population)
                # 5
                population = re.sub(
                    r"无特定人群|多数患者为|多3～13倍|以上最多见|发生率高于|也可发生在|主要发生在|该病好发于|好发年龄为|年岁分布于|无特殊人群|HIV感染者|经常日晒的|发病只占15%|IPH通常在|皮肤血管瘤|患者年龄在",
                    ' ', population)
                # 4
                population = re.sub(
                    r"最常见于|等也常见|往往不顾|可发生于|主要见于|发病率高|多发生在|大多见于|之比率为|患儿居多|较肥胖的|患者略多|本病罕见|多发生于|发病年龄|更易感染|尤其是在|发病最多|较多发于|之前发病|均可发病|以前发病|都有可能",
                    ' ', population)
                # 3
                population = re.sub(
                    r"大多数|聚集性|易感性|四十岁|者居多|常见于|的3倍|对见于|大多为|为最多|为多见|略多于|无明显|主要以|仅见于|多数为|大多在|中发病|无差异|但多在|既往有|稍多于|常发于|多见于|发生于|多发于|年龄为|主要是|之比为|发病率|患病率|比例为|尤其是|多数是",
                    ' ', population)
                # 2
                population = re.sub(
                    r"全部|一定|遗传|背景|稍多|其次|多有|也可|因此|相对|跳水|仅限|特点|冲动|传播|气体|几乎|任何|阶段|两个|高峰|常起|最多|起病|不同|本病|该病|年龄|为多|少于|较多|左右|约占|少见|病人|肾癌|发病|多与|之间|以后|约为|平均|居多|发生|多见|多于|见于|好发|常在|发于|多发|多在|可在|以上|以下|尤其|一般|多为|比例|略多|患者",
                    ' ', population)
                # 1
                population = re.sub(r"是|约|如|易|曾|且|常|现|史|者|均|在|高|有|岁|但|比|于|的|以|较|等|为|在|略|见|占|期|段", ' ', population)
                population = re.sub(r"或|和|及|[,，、。]", ' ', population)
                #
                population = re.sub(r"男性|男", ' 男 ', population)
                population = re.sub(r"女性|女", ' 女 ', population)
                population = re.sub(r"产妇", ' 产妇 ', population)
                population = re.sub(r"孩子|孩", ' 孩子 ', population)
                population = re.sub(r"发育", ' 发育 ', population)
                population = re.sub(r"新生儿", ' 新生儿 ', population)
                population = re.sub(r"婴儿|婴", ' 婴儿 ', population)
                population = re.sub(r"幼儿", ' 幼儿 ', population)
                population = re.sub(r"学龄前", ' 学龄前 ', population)
                population = re.sub(r"儿童|童", ' 儿童 ', population)
                population = re.sub(r"青春", ' 青春 ', population)
                population = re.sub(r"青年人|青年", '青年 ', population)
                population = re.sub(r"青少年人|青少年", ' 青少年 ', population)
                population = re.sub(r"中青年人|中青年", ' 中青年 ', population)
                population = re.sub(r"青壮年人|青壮年", ' 青壮年 ', population)
                population = re.sub(r"年轻人|年轻", ' 年轻 ', population)
                population = re.sub(r"青中年人|青中年", '青中年 ', population)
                population = re.sub(r"中年人|中年", '中年 ', population)
                population = re.sub(r"成年人|成年|成人", ' 成年 ', population)
                population = re.sub(r"中老年人|中老年", ' 中老年 ', population)
                population = re.sub(r"老年人|老年", '老年 ', population)
                population = re.sub(r"", '-', population)

                population = re.sub(r"\d|-|—|－|～|~|\.|:|∶|%|/", '', population)
                print(population.split(' '))
                # for population in population.split(' '):
                #     # print(population)
                #     population_set.add(population)

                # print(population)
                # print('/'.join(jieba.cut(population)))
                # words = preg.cut(population, HMM=False, use_paddle=False)
                # for word, pos in words:
                #     if pos in ['n', 'nr', 't']:
                #         population_set.add(word)
                #     print(word, pos, end=" ")
                # print('\n')
            # elif population != "":
            #     population = re.sub(r"多发于|发于|多发|多发生于|发生于|发生|多见于|多见|见于|于|好发|常在", '', population)
            #     population = re.sub(r"尤其是在|尤其是|尤其|主要是|但", '', population)
            #     population = re.sub(r"或|和|及|[,，、。]|的", ' ', population)
            #     for population in population.split(' '):
            #         # print(population)
            #         population_set.add(population)
        # if '发于' in name:
        #     print(f"发于 {name.find('发于')} {name}")
        #     print(f"\t{name[name.find('发于')+2:]}")
        # if '见于' in name:
        #     print(f"见于 {name.find('见于')} {name}")
        #     print(f"\t{name[name.find('见于')+2:]}")
        # if '发生于' in name:
        #     print(f"发生于 {name.find('发生于')} {name}")
        #     print(f"\t{name[name.find('发生于')+3:]}")
        # if '玩手机' in name:
        #     print(f"{name}")
    for p in population_set:
        print(p)
    print(len(population_set))


def population2():
    disease = matcher.match('disease')
    word_dict = {}
    ignore_list = []
    population_list = ['儿童']
    for disease in disease:
        if disease.get('population') is not None and disease['population'] != "":
            population = ' '.join(disease['population'])
            words = jieba.cut(population)
            # print('/'.join(words))
            for word in words:
                if word_dict.get(word) is not None:
                   word_dict[word] += 1
                else:
                    word_dict[word] = 1
                    # print(word)
    population_dict = dict(sorted(word_dict.items(), key= lambda kv:(kv[1], kv[0]), reverse=True))
    print(population_dict)
    for key, value in population_dict.items():
        print(f"{key},{value}")
    #     flag = input()
    #     if flag == "":
    #         population_list.append(key)
    #     else:
    #         ignore_list.append(key)
    # print(ignore_list)
    # print(population_list)


def cure_period():
    cure_period_set = set()
    disease = matcher.match('disease')
    for disease in disease:
        if disease.get('cure_period') is not None and disease['cure_period'] != "":
            cure_period = disease['cure_period']
            if '终身' in cure_period:
                cure_period = re.sub(r'个|左右', '', cure_period)
                cure_period_set.add(cure_period)
    for c in cure_period_set:
        print(c)


# 6/4/20
def symptom_brief():
    symptom = matcher.match('symptom')
    for symptom in symptom:
        if symptom.get('brief') is not None:
            symptom['brief'] = re.sub(r'\n\n', '\n', symptom['brief'])
            graph.push(symptom)


if __name__ == '__main__':
    symptom_brief()
